package servlet;

import com.alibaba.fastjson.JSON;
import entity.Movie;
import service.MovieService;
import service.impl.MovieServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

@WebServlet("/GetByPageAjaxServlet")
public class GetByPageAjaxServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取页码
        String pageNo=request.getParameter("pageNo");
        Integer pageSize=3;
        if(pageNo==null){
            pageNo="1";
        }
        MovieService movieService=new MovieServiceImpl();
        //分页查询数据
        List<Movie> list=movieService.getMovieByPage(Integer.valueOf(pageNo),pageSize);
        //统计数据总条数
        int totalCount=movieService.count();
        //计算总页数
        int totalPage=totalCount%pageSize==0?totalCount/pageSize:(totalCount/pageSize)+1;

        HashMap<String,Object> hashMap=new HashMap<>();
        hashMap.put("list",list);
        hashMap.put("totalCount",totalCount);
        hashMap.put("totalPage",totalPage);
        hashMap.put("pageNo",Integer.valueOf(pageNo));

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out=response.getWriter();
        String json= JSON.toJSONString(hashMap);
        out.print(json);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
